package com.my12306.user.service.auth.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.my12306.common.util.PageUtils;
import com.my12306.common.util.SnowflakeIdWorker;
import com.my12306.user.dao.auth.PermissionDao;
import com.my12306.user.model.po.auth.PermissionEntity;
import com.my12306.user.model.vo.PermissionVo;
import com.my12306.user.service.auth.PermissionService;
import com.my12306.user.service.auth.RolePermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.my12306.common.util.CommentUtils.getPoToVo;


@Service("permissionService")
public class PermissionServiceImpl extends ServiceImpl<PermissionDao, PermissionEntity> implements PermissionService {
    @Autowired
    private RolePermissionService rolePermissionService;
    @Resource
    private PermissionDao permissionDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        return new PageUtils();
    }

    /**
     * 返回树形菜单
     *
     * @param user_id
     * @return
     */
    @Override
    public List<PermissionEntity> getUserPermListByUser_id(long user_id) {
        //根据用户id查出所有用户权限
        List<PermissionEntity> entityList = getUserAllPermByUser_id(user_id);
        List<PermissionEntity> parent = entityList.stream().parallel().map(x -> {
            if (x.getParentId() == 0) {
                return x;
            }
            return null;
        }).filter(x -> x != null).collect(Collectors.toList());

        List<PermissionEntity> treeList = parent.stream().map(x -> {
            if (!x.getMenuId().equals(1)) {
                x.setList(getChildTreeMenue(x, entityList));
            }
            return x;
        }).collect(Collectors.toList());
//        System.out.println("===父id=-=================");
//        System.out.println(parent);
//        System.out.println("========树形菜单==========");

        return treeList;
    }


    public List<PermissionEntity> getChildTreeMenue(PermissionEntity parent, List<PermissionEntity> allPermisses) {

        List<PermissionEntity> collect = allPermisses.stream().parallel().filter(x -> {
            return parent.getMenuId().equals(x.getParentId()) && x.getType() < 2;
        }).map(x -> {
            System.out.println(x);
            List<PermissionEntity> childTreeMenue = getChildTreeMenue(x, allPermisses);
            if (childTreeMenue != null)
                x.setList(childTreeMenue);
            return x;
        }).sorted((x1, x2) -> {
            return x1.getMenuId().compareTo(x2.getMenuId());
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 查询所有菜单权限
     *
     * @param userId
     * @return
     */
    @Override
    public List<String> getUserPermissionByUser_id(long userId) {
        return this.baseMapper.queryPermissionByUserId(userId);
    }

    /**
     * 根据用户id 查出所有的权限id
     *
     * @param user_id
     * @return
     */
    @Override
    public List<Long> getUserPermIdByUser_id(long user_id) {
        return null;
    }

    /**
     * 根据用户id查出所有权限
     *
     * @param user_id
     * @return
     */
    @Override
    public List<PermissionEntity> getUserAllPermByUser_id(long user_id) {
        return this.baseMapper.selectAllPermByUser_id(user_id);
    }


    /**
     * 根id 修改权限
     *
     * @param entity
     * @return
     */
    @Override
    public Boolean updatePermByid(PermissionEntity entity) {
        return null;
    }

    @Override
    public List<PermissionVo> getPermsNotButtonList() {
        QueryWrapper<PermissionEntity> wrapper = new QueryWrapper<PermissionEntity>();
        wrapper.ne("type", 2);
        List<PermissionEntity> permissionEntities = this.baseMapper.selectList(wrapper);
        return permissionEntities.stream().map(x -> {
            PermissionVo permissionVo = new PermissionVo();
            getPoToVo(x, permissionVo);
            return permissionVo;
        }).collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deletePermById(Long permId) {
        System.out.println(permId);
        //1.先查询出所有改id及其子权限的id
        List<Long> allIds = new ArrayList<>();
        selectPermId(permId, allIds);
        System.out.println(allIds);
        allIds.add(permId);
        //2.删除所有改权限id对应的 角色关系
        System.out.println(allIds);
        rolePermissionService.deleteRolePermByPermIds(allIds);
        //3.删除所有权限
        permissionDao.deleteBatchPermissionByIds(allIds);
    }

    @Override
    public List<Long> queryPermIdByParentId(Long parentId) {
        return this.baseMapper.queryPermIdByParentId(parentId);
    }

    @Override
    public void savePermission(PermissionVo permissionVo) {
        if (permissionVo != null && permissionVo.getName() != null) {
            PermissionEntity permissionEntity = new PermissionEntity();
            getPoToVo(permissionVo, permissionEntity);
            permissionEntity.setMenuId(SnowflakeIdWorker.generateId());
            permissionEntity.setCreateDate(new Date());
            permissionEntity.setUpdateDate(new Date());
            this.baseMapper.insert(permissionEntity);
        }
    }

    public List<Long> selectPermId(Long parentId, List<Long> ids) {
        List<Long> childIds = queryPermIdByParentId(parentId);
        System.out.println("ids====>>>>" + ids);
        ids.stream().forEach(x -> {
            if (childIds.contains(x)) childIds.remove(x);
        });
        if (childIds != null && childIds.size() > 0) {
            ids.addAll(childIds);
        }
        childIds.stream().forEach(x -> {
            List<Long> permIds = selectPermId(x, ids);
            ids.addAll(permIds);
        });
        return childIds;
    }

}
